﻿using System.Net;
using System.Net.Sockets;
using System.Text;

namespace SocketServer
{
    public class UDPServer
    {
        private Socket server;
        private byte[] buffer = new byte[1024];
        private List<EndPoint> clients = new List<EndPoint>();
        private int port = 8844;

        /// <summary>
        /// 启动服务器
        /// </summary>
        public void StartServer()
        {
            IPEndPoint IPEndPoint = new(IPAddress.Parse("127.0.0.1"), port);
            server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            server.Bind(IPEndPoint);

            Console.WriteLine("服务器已启动，等待客户端连接...");
            ReceiveFromClients();
        }

        /// <summary>
        /// 关闭服务器
        /// </summary>
        public void CloseServer()
        {
            server.Close();
            clients.Clear();
        }

        /// <summary>
        /// 消息广播
        /// </summary>
        /// <param name="message"></param>
        private void BroadcastToClients(string message)
        {
            byte[] data = Encoding.UTF8.GetBytes(message);
            foreach (var client in clients)
            {
                server.SendTo(data, client);
            }
        }

        /// <summary>
        /// 接收来自客户端信息
        /// </summary>
        private void ReceiveFromClients()
        {
            EndPoint clientEndPoint = new IPEndPoint(IPAddress.Any, 0);
            server.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref clientEndPoint, new AsyncCallback(ReceiveCallback), null);
        }

        /// <summary>
        /// 数据接收
        /// </summary>
        /// <param name="ar"></param>
        private void ReceiveCallback(IAsyncResult ar)
        {
            EndPoint clientEndPoint = new IPEndPoint(IPAddress.Any, 0);
            int bytesRead = server.EndReceiveFrom(ar, ref clientEndPoint);
            string receivedMessage = Encoding.UTF8.GetString(buffer, 0, bytesRead);
            Console.WriteLine("接收到来自客户端的消息: " + receivedMessage);

            if (!clients.Contains(clientEndPoint))
            {
                clients.Add(clientEndPoint);
                Console.WriteLine("客户端已连接: " + clientEndPoint);
            }

            BroadcastToClients(receivedMessage);
            ReceiveFromClients();
        }
    }
}